from fastapi import APIRouter, Request, HTTPException
from fastapi.responses import StreamingResponse, JSONResponse
from pydantic import BaseModel

from database.database import engine
from sqlalchemy import text

from .category import select_category_head, select_category_children

from .banner import select_banner_type
from .goods import select_goods_category_limit


router = APIRouter(
    prefix='/home',
    tags = ['系统首页']
)

@router.get("/category/head")
def category_head():
    result = select_category_head()
    if result:
        result_dict = []
        for row in result:
            category_dict = row._asdict()
            category_children = select_category_children(category_dict["id"])
            category_dict["children"] = [child._asdict() for child in category_children]
            category_goods = select_goods_category_limit(category_dict["id"], 9)
            category_dict["goods"] = [child._asdict() for child in category_goods]
            result_dict.append(category_dict)

        data = { "code": 0, "message": "操作成功" }
        data["result"] = result_dict
        return JSONResponse(status_code=200, content=data)
    else:
        data = { "code": 500, "message": "操作失败" }
        return JSONResponse(status_code=200, content=data)


@router.get("/banner")
def banner(distributionSite:str="1"):
    result = select_banner_type(distributionSite)
    if result:
        result_dict = [row._asdict() for row in result]

        data = { "code": 0, "message": "操作成功" }
        data["result"] = result_dict
        return JSONResponse(status_code=200, content=data)
    else:
        data = { "code": 2, "msg": "操作失败" }
        return JSONResponse(status_code=201, content=data)


@router.get("/goods")
def goods():
    result = select_category_head()
    if result:
        result_dict = []
        for row in result:
            category_dict = row._asdict()
            category_children = select_category_children(category_dict["id"])
            category_dict["children"] = [child._asdict() for child in category_children]
            category_goods = select_goods_category_limit(category_dict["id"], 8)
            category_dict["goods"] = [child._asdict() for child in category_goods]
            result_dict.append(category_dict)

        data = { "code": 0, "message": "操作成功" }
        data["result"] = result_dict
        return JSONResponse(status_code=200, content=data)
    else:
        data = { "code": 2, "msg": "操作失败" }
        return JSONResponse(status_code=201, content=data)
